package guitforl.wrappers

import guitforl.traits.UpdateableWidget
import org.jfree.chart.{JFreeChart, ChartFactory, ChartPanel}
import org.jfree.chart.plot.PlotOrientation
import javax.swing.JPanel
import guitforl.data.readers.DataReader
import org.jfree.data.category.{DefaultCategoryDataset, CategoryDataset}
import org.jfree.data.xy.{XYDataset, DefaultXYDataset, XYSeries, XYSeriesCollection}
import guitforl.wrappers.ChartTypes._
import java.awt.Dimension

class ChartWrapper(val widgetName: String,
                   private val caption: String,
                   private val xCaption:String,
                   private val yCaption:String,
                   private val chartType : Value,
									 private val dataSource: Seq[DataReader]) extends JPanel with UpdateableWidget {

	 setLayout(LayoutFactory.createCellLayout)

   val chartPanel = createEmptyChartPanel
   add(chartPanel);

  def update():Unit = {
	  val newChart = createChartFromType
    chartPanel.setChart(newChart)
  }

	private def createChartFromType():JFreeChart = {
		chartType match{
			case LINE => return createXYLineChart(createChartDataset)
			case POINTS => return createScatterPlot(createChartDataset)
		}
	}

	def createEmptyChartPanel() = {
		new ChartPanel(createScatterPlot(new DefaultXYDataset))
	}

	private def createChartDataset() = {
		val chartData = dataSource.map(_.getColumnsDoubleList)
		val chartDataSet = new DefaultXYDataset

		var seriesNumber = 0;
	  for(chartDataPice <- chartData){
		  chartDataSet.addSeries("data" + seriesNumber, chartDataPice)
		  seriesNumber+=1
	  }
		chartDataSet
	}

	private def createScatterPlot(dataset : XYDataset) = {
		ChartFactory.createScatterPlot(
            caption,
            xCaption,
            yCaption,
            dataset,
            PlotOrientation.VERTICAL,
            true,
            true,
            false
			)
	}

	private def createXYLineChart(dataset : XYDataset) = {
		ChartFactory.createXYLineChart(
		    caption,                  // chart title
		    xCaption,                      // x axis label
		    yCaption,                      // y axis label
		    dataset,                  // data
		    PlotOrientation.VERTICAL,
		    true,                     // include legend
		    true,                     // tooltips
		    false                     // urls
		)
	}

}
